<?php
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{
    public function explain()
    {
        $fuc_name = (string)$this->get_c2_type();
        if(empty($fuc_name))
        {
            return $this->write_log_return('C2类型参数为空', NS_CDS_FAIL);
        }
        return $this->save_exec_log($this->$fuc_name());
    }

    /**
     * 注入CDN，主媒资不注入
     * @return array
     */
    public function video()
    {
        return $this->is_ok(NS_CDS_CDN_SUCCE, '成功');
    }
    /**
     * 注入CDN，分集不注入
     * @return array
     */
    public function index()
    {
        return $this->is_ok(NS_CDS_CDN_SUCCE, '成功');
    }
    public function media()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->media_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        $arr_video_info = $this->get_video_info();
        if (empty($arr_video_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }
        $cdn_policy_id = strlen($this->get_c2_info('nns_cdn_policy')) > 0 ? $this->get_c2_info('nns_cdn_policy') : 'cdn1';
        if(isset($this->arr_source_config["import_msp_cdn_policy"]) && strlen($this->arr_source_config["import_msp_cdn_policy"]) > 0)
        {
            $temp_import_msp_cdn_policy = trim($this->arr_source_config["import_msp_cdn_policy"]);
            $cdn_policy_id = strlen($temp_import_msp_cdn_policy) > 0 ? $temp_import_msp_cdn_policy : $cdn_policy_id;
        }
        $data = array();
        //片源注入数据结构
        $data['func'] = 'add_content_by_cdn_policy';
        $data['name'] = $arr_media_info['base_info']['nns_name'];
        $data['url'] = $this->get_c2_info('nns_file_path');
        $data['cdn_policy_id'] = $cdn_policy_id;
        $data['id'] = $cdn_import_id;
        $data['live'] = 0;
        $data['filetype'] = $arr_media_info['base_info']['nns_filetype'];
        $data['asset_id'] = $arr_media_info['base_info']['nns_import_id'];
        $data['cp'] = $arr_media_info['base_info']['nns_cp_id'];//$arr_video_info['base_info']['nns_producer'];
        $data['transfer_rate'] = 0;
        $data['ingress_capacity'] = 0;
        $data['bitrate'] = $arr_media_info['base_info']['nns_kbps'];
        $data['cdn_ext_source_id'] = strlen($this->arr_source_config["clip_custom_origin_id"]) > 0 ? $this->arr_source_config["clip_custom_origin_id"] : "";
        $data["domain"] = isset($arr_media_info['base_info']["nns_domain"]) ? $arr_media_info['base_info']["nns_domain"] : 257;
        $data['cms_id'] = $arr_media_info['base_info']['nns_cp_id'];
        $arr_ext_info = array();
        if(isset($arr_media_info['base_info']['nns_ext_info']) && strlen($arr_media_info['base_info']['nns_ext_info'])>0)
        {
            $arr_ext_info = json_decode($arr_media_info['base_info']['nns_ext_info'],true);
        }
        if(isset($arr_media_info['base_info']['nns_ext_url']) && strlen($arr_media_info['base_info']['nns_ext_url'])>0)
        {
            $arr_ext_url = json_decode($arr_media_info['base_info']['nns_ext_url'],true);
        }
        if(isset($arr_ext_info['node_id']))
        {
            $data['node_id'] = isset($arr_ext_info['node_id']) ? $arr_ext_info['node_id'] : '';
            $data['nmds_id'] = isset($arr_ext_info['list_ids']) ? $arr_ext_info['list_ids'] : '';
            //$data['cp'] = $arr_media_info['base_info']['nns_import_source'];
            $data["org_download_path"] = $arr_media_info['base_info']["nns_url"];
            $data["business_type"] = isset($arr_ext_url['business_type']) ? $arr_ext_url['business_type'] : "iptv";
        }
        $data['file_size'] = !empty($this->get_c2_info('nns_file_size')) ? $this->get_c2_info('nns_file_size') : $arr_ext_info['size'];
        $data['sop_id'] = $this->str_sp_id;
        $data['correlate_id'] = $this->get_c2_info('message_id');
        $this->obj_dom = new DOMDocument("1.0", 'utf-8');
        $xml = $this->_make_array_xml($data);
        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params,$data,$xml);
    }

    /**
     * 片源删除
     */
    public function media_destroy()
    {
        global $g_core_userid;
        $str_core_userid = $g_core_userid;
        unset($g_core_userid);
        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }

        $data = array();
        //片源注入数据结构
        $data['func'] = 'delete_content';
        $data['id'] = $cdn_import_id;
        $data['live'] = 0;
        $data['user'] = $str_core_userid;
        $data['is_del_file'] = 1;
        $arr_ext_info = array();
        if(isset($arr_media_info['base_info']['nns_ext_info']) && strlen($arr_media_info['base_info']['nns_ext_info'])>0)
        {
            $arr_ext_info = json_decode($arr_media_info['base_info']['nns_ext_info'],true);
        }
        if(isset($arr_ext_info['node_id']))
        {
            $data['node_id'] = isset($arr_ext_info['node_id']) ? $arr_ext_info['node_id'] : '';
            $data['list_ids'] = isset($arr_ext_info['list_ids']) ? $arr_ext_info['list_ids'] : '';
            $data['cms_id'] = $arr_media_info['base_info']['nns_cp_id'];
            $data['cp'] = $arr_media_info['base_info']['nns_import_source'];
        }
        $data['sop_id'] = $this->str_sp_id;
        $data['correlate_id'] = $this->get_c2_info('message_id');
        $this->obj_dom = new DOMDocument("1.0", 'utf-8');
        $xml = $this->_make_array_xml($data);
        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => 'DELETE', //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params,$data,$xml);
    }
    /**
     * 生成xml
     * @param unknown $data
     * @param string $obj_parent
     * @param string $flag
     */
    private function _make_array_xml($data,$obj_parent=null,$flag=true)
    {
        $obj_parent = $obj_parent === null ? $this->_make_xml($this->obj_dom, 'msp')  : $obj_parent;
        if(empty($data) || !is_array($data))
        {
            return $flag ? $this->obj_dom->saveXML() : true;
        }
        foreach ($data as $key => $val)
        {
            if($key == 'content_mng_xml')
            {
                $val = base64_encode($val);
            }
            if(!is_array($val))
            {
                $this->_make_xml($obj_parent, $key,$val);
            }
            else if(!empty($val) && is_array($val))
            {
                $obj_parent = $this->_make_xml($obj_parent, $key);
                $this->_make_array_xml($val,$obj_parent,false);
            }
        }
        return $flag ? $this->obj_dom->saveXML() : true;
    }
    /**
     * 组装基础dom对象类
     * @param object $dom   dom对象
     * @param object $parent 父级对象
     * @param string $key 键
     * @param string $val 值
     * @return object
     * @date 2015-05-04
     */
    private function _make_xml($parent, $key, $val = null, $arr_attr = null)
    {
        $$key = isset($val) ? $this->obj_dom->createElement($key) : $this->obj_dom->createElement($key);
        if (!empty($arr_attr) && is_array($arr_attr))
        {
            foreach ($arr_attr as $attr_key => $attr_val)
            {
                $domAttribute = $this->obj_dom->createAttribute($attr_key);
                $domAttribute->value = $attr_val;
                $$key->appendChild($domAttribute);
                $this->obj_dom->appendChild($$key);
            }
        }
        if(isset($val) && strlen($val) >0)
        {
            $$key->appendChild($this->obj_dom->createCDATASection($val));
        }
        $parent->appendChild($$key);
        unset($parent);
        return $$key;
    }
    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $params array(
     *       'nns_task_type' =>类型,
     *       'nns_action' => 行为动作，
     *       'nns_content' => 注入XML内容
     * );
     * @return array('ret','reason');
     */
    public function execute($params,$data,$xml)
    {
        //生成CDN工单唯一ID
        $c2_correlate_id = $params['nns_id'] = $this->get_guid();
        $params['nns_result'] = NS_CDS_CDN_SUCCE;
        $reason = "注入成功";
        $params['nns_result'] = $cdn_code = NS_CDS_CDN_SUCCE;
        $task = $this->save_execute_import_content($xml);
        if($task['ret'] != 0)
        {
            $this->write_log_return($task['reason'], NS_CDS_FAIL);
            return $task;
        }
        $params['nns_url'] = $task['data_info']['base_dir'];
        \ns_core\m_load::load_np("np_http_curl.class.php");
        $obj_curl = new np_http_curl_class();
        $arr_header = array(
            "Content-type: multipart/form-data;charset=\"utf-8\"",
        );
        $params['nns_send_time'] = date("Y-m-d H:i:s");
        $file_ret = $obj_curl->do_request('post',$this->arr_sp_config['cdn_send_mode_url'],$data,$arr_header,60);
        /*$file_ret = '<?xml version="1.0" encoding="utf-8" ?><nn_api><result seqno="" ret="0" reason="ok"/><content id="176b61bb438284e7419a396d73785bfc" /></nn_api>';*/
        $this->write_log_return('[访问CDN片源注入,CURL接口返回]：' . var_export($file_ret,true));
        $params['nns_notify_time'] = date("Y-m-d H:i:s");
        $curl_info = $obj_curl->curl_getinfo();
        //$curl_info['http_code'] = '200';
        //发送CDN时，发生的异常处理【理解为发送状态】
        if($curl_info['http_code'] != '200')
        {
            $err_msg = '[访问片源注入失败,CURL接口地址]：'.$this->arr_sp_config['cdn_send_mode_url'].'[HTTP状态码]：'.$curl_info['http_code'].'[HTTP错误]：'.$obj_curl->curl_error().'；参数：'.var_export($data,true);
            $this->write_log_return(var_export($err_msg,true),NS_CDS_CDN_FAIL);
            $reason = $params['nns_result_fail_reason'] = '访问片源注入失败,HTTP状态码：'.$curl_info['http_code'];
            $params['nns_result'] = $cdn_code = NS_CDS_CDN_FAIL;
            unset($obj_curl);
            $build_c2 = $this->build_c2_log($params);
            if($build_c2['ret'] != NS_CDS_SUCCE)
            {
                return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
            }
            return $this->is_ok($cdn_code,$reason);
        }

        unset($obj_curl);
        //CDN同步反馈，为了兼容数据库重复查询，故此处不调用is_notify_ok
        $result_info = json_decode(json_encode(@simplexml_load_string($file_ret)),true);//解析CURL返回结果
        if($result_info['result']['@attributes']['ret'] != '0')
        {
            $err_msg = '[访问片源注入成功,CURL接口地址]：'.$this->arr_sp_config['cdn_send_mode_url'].'[接口返回结果]：'.var_export($result_info,true).'；参数：'.var_export($data,true);
            $this->write_log_return(var_export($err_msg,true),NS_CDS_CDN_FAIL);
            $reason = isset($result_info['result']['@attributes']['reason']) && !empty($result_info['result']['@attributes']['reason']) ? $result_info['result']['@attributes']['reason'] : '注入失败';
            $cdn_code = NS_CDS_CDN_NOTIFY_FAIL;
            $log_data = \m_config::write_execute_cdn_notify_content($this->str_sp_id,$c2_correlate_id,$file_ret);
            $notify_url = $log_data['data_info']['base_dir'];
            $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_FAIL;
            $params['nns_notify_fail_reason'] = $reason;
            $params['nns_notify_result_url'] = $notify_url;
            $params['nns_notify_time'] = date('Y-m-d H:i:s');
        }
        else
        {
            $err_msg = '[访问片源注入成功,CURL接口地址]：'.$this->arr_sp_config['cdn_send_mode_url'].'[接口返回结果]：'.var_export($result_info,true).'；参数：'.var_export($data,true);
            $this->write_log_return(var_export($err_msg,true));
            $reason = isset($result_info['result']['@attributes']['reason']) && !empty($result_info['result']['@attributes']['reason']) ? $result_info['result']['@attributes']['reason'] : $reason;

            $log_data = \m_config::write_execute_cdn_notify_content($this->str_sp_id,$c2_correlate_id,$file_ret);
            $notify_url = $log_data['data_info']['base_dir'];
            $params['nns_notify_result'] = $cdn_code;
            $params['nns_notify_fail_reason'] = '';
            $params['nns_notify_result_url'] = $notify_url;
            $params['nns_notify_time'] = date('Y-m-d H:i:s');
            //修改vod_media的content_id
            \nl_vod_media_v2::edit(\m_config::get_dc(),array('nns_content_id'=>$result_info['content']['@attributes']['id']),$this->get_c2_info("nns_ref_id"));
        }
        $build_c2 = $this->build_c2_log($params);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }
        return $this->is_ok($cdn_code,$reason);
    }
}
